from flask import Flask, request, jsonify, render_template
from main import *
from flask_cors import CORS
from bs4 import BeautifulSoup

app = Flask(__name__)
# app.debug = True  # 启用调试模式
CORS(app, resources=r'/*')  # 这将为所有路由启用 CORS


@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['file']
    df = main(file)
    # 这里可以添加翻译逻辑，例如使用Google Cloud Translation API
    # 翻译后的数据可以存储在另一个DataFrame或列表中
    return jsonify(df)


@app.route("/feishu", methods=['POST'])
def get_feishu_herf():
    href_list = []
    host = "https://kcnngnrccaw2.feishu.cn"
    html_str = request.form.get('text')
    soup = BeautifulSoup(html_str, 'html.parser')
    lis = soup.find_all('li', class_='file-list-item selected')
    for item in lis:
        a = item.find('a', draggable="false")
        href = host + a['href']
        href_list.append(href)
    href_str = '\n'.join(href_list)
    return jsonify({"text": href_str})


@app.route('/table', methods=['POST'])
def deal_table():
    data = request.form
    language = ['auto']
    language.extend([
        'fra',
        'de',
        'jp',
        'kor',
        'pt',
        'spa',
        'vie',
        'id',
        'it',
        'th',
        'tr',
        'ru',
        'cht',
    ])
    language.extend(data.getlist('languages'))
    text = []
    for item in data.getlist('text'):
        temp = item.split("\n")
        # 去除/n/r/t等特殊字符
        temp = [x.replace("\n", "").replace("\r", "").replace("\t", "") for x in temp]
        # 删除空字符串
        temp = [x for x in temp if x]
        text.extend(temp)

    body_dict = {"language": language, "text": text}
    df = main(formData=body_dict)

    return jsonify(df)


@app.route("/index")
def index():
    return render_template("index.html")


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8080, debug=True)
